package com.intelligentmeterreadingsys.waterlist.copywater.activity;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONObject;
import com.android.rfid.RfidHelper;
import com.intelligentmeterreadingsys.R;
import com.intelligentmeterreadingsys.httpserver.RequestUrl;
import com.intelligentmeterreadingsys.httpserver.UploadHttpClient;
import com.intelligentmeterreadingsys.povo.UserWaterVO;
import com.intelligentmeterreadingsys.povo.WaterInfoVO;
import com.intelligentmeterreadingsys.util.BluetoothHelp;
import com.intelligentmeterreadingsys.util.SafetyExitUtil;
import com.intelligentmeterreadingsys.util.SharedPreferenceUtil;
import com.intelligentmeterreadingsys.util.TipHelper;
import com.intelligentmeterreadingsys.waterlist.copywater.db.CopyWaterDao;
import dbhelper.XmlNameHelper;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 抄表
 * 
 * @author king
 * 
 */
public class CopyWaterRFIDActivity extends Activity implements OnClickListener {
	  public static final int ITEM0=Menu.FIRST;//系统值
	  private final static int DIALOG=1;
	  public int FRIDtype=2;//RFID协议
	   
	public String xieyi="15693";
	public Button button1;// 读卡
	public Button button2;// 拍照
	public Button button3;// 保存
	public Button button4;// 上传

	public EditText edit1;// 本月水表刻度
	public EditText edit2;// 备注

	public TextView textview1;// 用户编号
	public TextView textview2;// 用户姓名
	public TextView textview3;// 水表地址
	public TextView textview4;// 水表编号
	public TextView textview5;// 水表口径
	public TextView textview6;// 上月刻度
	public TextView textview7;// 本月用水量
	
	public SafetyExitUtil safe=null;
	public String RFIDnumber;

	public RfidHelper rh;// 读卡帮助对象

	public ProgressDialog pd;// 读卡进度条

	public boolean isStop = true;
	
	public boolean issave=false;
	public BluetoothHelp bluehelp;
	public long time;
    public UserWaterVO water=null;
    
    public boolean isupload=false;
    public String readtype="终端读卡";
    public String[] readdate;
    public boolean b=true;
  

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.copywatermain);
		init();
		
		
	}

	/**
	 * 初始化控件
	 */
	public void init() {
		
		readtype="终端读卡";
		SharedPreferenceUtil sh=new SharedPreferenceUtil(this);
		sh.insertValue(XmlNameHelper.isSafe, true);
		button2 = (Button) findViewById(R.id.copywater_photograph_button);
		button3 = (Button) findViewById(R.id.copywater_save_button);
		button4 = (Button) findViewById(R.id.copywater_upload_button);
		button1=(Button)findViewById(R.id.copywater_readcard_button);
		button1.setOnClickListener(this);
		button2.setOnClickListener(this);
		button3.setOnClickListener(this);
		button4.setOnClickListener(this);
		edit1 = (EditText) findViewById(R.id.copywater_thismoth_caliber);
		edit2 = (EditText) findViewById(R.id.copywater_des);
		//监听输入
		edit1.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {				
				if(water!=null){
					if(!TextUtils.isEmpty(s.toString())){
						Double usewater=Double.parseDouble(s.toString())-water.getLastmonthwater();
						
						textview7.setText(usewater+"");
						
						if(usewater>water.getAlarmlimit()||usewater<water.getLowalarmlimit()){
							textview7.setTextColor(Color.RED);
							//edit1.setTextColor(Color.RED);
						}else{
							//edit1.setTextColor(Color.BLACK);
							textview7.setTextColor(Color.BLACK);
						}
					}else{
						textview7.setText("");
					//	edit1.setTextColor(Color.BLACK);
						textview7.setTextColor(Color.BLACK);
						
					}
					
				}
				
			}
		});

		textview2 = (TextView) findViewById(R.id.copywater_username);
		textview1 = (TextView) findViewById(R.id.copywater_usernumber);
		textview3 = (TextView) findViewById(R.id.copywater_wateradds);
		textview4 = (TextView) findViewById(R.id.copywater_waternumber);
		textview5 = (TextView) findViewById(R.id.copywater_caliber);
		textview6 = (TextView) findViewById(R.id.copywater_lastmoth_scale);
		textview7 = (TextView) findViewById(R.id.copywater_thismoth_content);
		

		rh = RfidHelper.getInstance();
		rh.setCardType(FRIDtype);
		rh.open();
		rh.setAllNoOfTimes(1);
		rh.setTimeInterval(50);
		// 设置激活读卡器后等待的时间.sdk默认10
		rh.setPingTimeInterval(10);
		isStop=true;
		
		bluehelp=new BluetoothHelp(this);
		bluehelp.init();
		
	}

	@Override
	public void onClick(View v) {
         
			if(button3.getId()==v.getId()){
				
				if(TextUtils.isEmpty(edit1.getEditableText().toString())){
					Toast.makeText(this, "还没输入刻度呢", 1000).show();
					return;
				}
				if(TextUtils.isEmpty(textview4.getText().toString())){
					Toast.makeText(this, "没有水表", 1000).show();
					return;
				}
			if(isupload||water.getIsupload().equals("1")){
				Toast.makeText(this, "已经上传了，不能再修改", 1000).show();
				return;
			}
			boolean b=	save();
			if(b){
				Toast.makeText(CopyWaterRFIDActivity.this, "保存成功", Toast.LENGTH_LONG).show();
				issave=true;
				return;
			}
			issave=false;
			}
			if(button4.getId()==v.getId()){
				if(TextUtils.isEmpty(textview4.getText().toString())){
					Toast.makeText(this, "没有水表", 1000).show();
					return;
				}
				if(!issave){
					Toast.makeText(CopyWaterRFIDActivity.this, "请保存后再上传", 1000).show();
					return;
				}
				if(isupload){
					Toast.makeText(CopyWaterRFIDActivity.this, "已经上传过了", 1000).show();
					return;
				}
				pd=new ProgressDialog(this);
				pd.setMessage("上传中....");
				pd.show();
				new Thread(){
					@Override
					public void run() {						
						RequestUrl Req = new RequestUrl(CopyWaterRFIDActivity.this);
						String url = Req.getUrl(RequestUrl.COPYWATERLIST);
					     SharedPreferenceUtil sh=new SharedPreferenceUtil(CopyWaterRFIDActivity.this);					     
						CopyWaterDao dao=new CopyWaterDao(CopyWaterRFIDActivity.this);
						WaterInfoVO waterinfo=dao.queryOneNoUpload(null,water.getWaterid(),"0");						
						Map<String, String> map = new HashMap<String, String>();
						Map<String, String> map1=new HashMap<String, String>();
						map1.put("waternumber", waterinfo.getWaternumber());
						map1.put("thismonthwater" + "", waterinfo.getThismonthwater()+"");		
						String usewater=(waterinfo.getThismonthwater()-waterinfo.getLastmonthwater())+"";		
						map1.put("usewater", usewater);
						map1.put("thisdate", waterinfo.getThisdate());
						map1.put("imsi", sh.getValue(XmlNameHelper.IMSI));
						map1.put("desc", waterinfo.getDesc());
						map1.put("sid", "0");
						map1.put("isnorfid", waterinfo.getIsNorfid());
						System.out.println("是否正常抄表"+waterinfo.getIsNorfid());
						Map<File, String> mapfile=new HashMap<File, String>();
						List<String> list=waterinfo.getImagepath();
						for(int i=0;i<list.size();i++){
							File file=new File(list.get(i));
							if(file.exists()){				
								map.put(file.getName(), "imagename");
								mapfile.put(file, "imagepath");
							}							
						}						
						dao.close();						
						try {							
						String respon=	UploadHttpClient.uploadSubmit(url, map, mapfile,map1);
							System.out.println(respon);
							if (respon.equals("error")) {
							   Message msg=UpoladHandle.obtainMessage();
							   msg.what=1;
							   UpoladHandle.sendMessage(msg);
							} else {
								pd.dismiss();
								JSONObject json=new JSONObject(respon);
								String message =json.getString("message");
								if(message.equals("no")){
									Message msg=UpoladHandle.obtainMessage();
									msg.what=2;
									UpoladHandle.sendMessage(msg);
									return;
								}else{
									Message msg=UpoladHandle.obtainMessage();
									msg.what=3;
									UpoladHandle.sendMessage(msg);
									return;
								}								
							}							
						} catch (Exception e) {
							Message msg=UpoladHandle.obtainMessage();
							msg.what=2;
							UpoladHandle.sendMessage(msg);
						}					
					}					
				}.start();
			}
			if (button2.getId() == v.getId()) {
				if(TextUtils.isEmpty(textview4.getText().toString())){
					Toast.makeText(this, "没有水表", 1000).show();
					return;
				}
               Bundle bundle=new Bundle();
               bundle.putString("otherid", water.getWaterid());
             
               bundle.putString("status", "2");
               bundle.putString("classname", "CopyWaterRFIDActivity");
               Intent intent=new Intent(CopyWaterRFIDActivity.this, ImageSwitcherActivity.class);
               intent.putExtras(bundle);
               startActivity(intent);
				//cameraMethod();
			}
				
          if(button1.getId()==v.getId()){
              isStop=true;
				if(!b){
					Toast.makeText(this,"已经在读卡中", Toast.LENGTH_SHORT).show();
					return;
				}
				pd=new ProgressDialog(this);
				pd.setMessage("正读卡中....");
				pd.show();
				initRFID(FRIDtype);
				time=System.currentTimeMillis();
				new Thread(){

					@Override
					public void run() {
                      b=false;
						
						while (isStop) {
							String id=RFIDnumber = "";
							if(readtype.equals("终端读卡")){	
							  id=RFIDnumber = rh.readIDString();
								
							}else{
								
								 id=RFIDnumber=bluehelp.getRfidId();
							}			
							
							if (!TextUtils.isEmpty(id)) {
								isStop = false;
								Message msg = MyHandler.obtainMessage();
								msg.what = 1;
								msg.obj = id;
								MyHandler.sendMessage(msg);
							}
							try {
								Thread.sleep(500);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
						
						super.run();
					
					}
					
				}.start();
			
          }
	}

	/**
	 * 保存
	 * 
	 * @return
	 */
	public boolean save() {
		boolean b=false;
		
		if(water.getIsupload().equals("1")){
			Toast.makeText(CopyWaterRFIDActivity.this, "已经上传过了不能再抄了", 1000).show();
			return false;
		}
		CopyWaterDao dao = new CopyWaterDao(this);
		b=dao.isPhotograph(water.getWaterid());
		if(textview7.getCurrentTextColor()==Color.RED&&b==false){
			Toast.makeText(CopyWaterRFIDActivity.this, "报警水表需拍照", 1000).show();
			dao.close();
			return false;
		}
		if(RFIDnumber!=null&&water!=null){
			Double thismothwater = Double.parseDouble(edit1.getEditableText()
					.toString());
			
			 b=dao.saveWater(water.getWaterid(), thismothwater,edit2.getEditableText().toString(),"0");
			 dao.close();
			
		}else{
			dao.close();
			return false;
			
		}
		
		
		return b;

	}

	/**
	 * 上传
	 * 
	 * @return
	 */
	public Handler UpoladHandle=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			if(msg.what==1){
				pd.dismiss();
				Toast.makeText(CopyWaterRFIDActivity.this, "请检查网络",
						1000).show();
			}else if(msg.what==2){
				pd.dismiss();
				Toast.makeText(CopyWaterRFIDActivity.this, "上传失败",
						1000).show();
			}else if(msg.what==3){
				pd.dismiss();
				Toast.makeText(CopyWaterRFIDActivity.this, "上传成功",
						Toast.LENGTH_LONG).show();
				CopyWaterDao dao=new CopyWaterDao(CopyWaterRFIDActivity.this);
				
				dao.uploadstatus(water.getWaterid());
				dao.close();
				
                   isupload=true;
			}
		}
		
	};

	
	/**
	 * 关闭读卡
	 */
	public void close() {
		isStop=false;
		if (rh != null) {
			rh.stopAutoRead();
			rh.close();
		}

	}

	@Override
	protected void onDestroy() {
		
		close();
		bluehelp.stop();
		super.onDestroy();
	}

	/**
	 * 展现数据
	 */
	public void viewdate(){
		
		textview1.setText(water.getNumber());
		textview2.setText(water.getName());
		textview3.setText(water.getAdds());
		textview4.setText(water.getWaternumber());
		textview5.setText(water.getMetercaliber());
		textview6.setText(water.getLastmonthwater()+"");
		if(water.getThismonthwater()==0){
			 edit1.setText("");
		}else{
			 edit1.setText(water.getThismonthwater()+"");
		}
	   
	    edit2.setText(water.getDesc());
	    if(water.getThismonthwater()!=0){
	    	 textview7.setText(water.getThismonthwater()-water.getLastmonthwater()+"");
	    }
	   
	    
		
	}
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		menu.add(0, ITEM0, 0, "短息通知");
		menu.add(0,ITEM0+1,0,"RFID协议");
		menu.add(0,ITEM0+2,0,"读卡方式");
		
		menu.findItem(ITEM0+1);
		return true;
		
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		if(item.getItemId()==ITEM0){
			if(water==null){
				Toast.makeText(CopyWaterRFIDActivity.this, "没查到用户无法发送", Toast.LENGTH_LONG).show();
				return false;
			}
			Uri smsToUri = Uri.parse("smsto:"); 
			String userwater=textview7.getText().toString();
		     Intent sendIntent = new Intent(Intent.ACTION_VIEW, smsToUri); 
		      sendIntent.putExtra("address", water.getPhone());   //电话号码，这行去掉的话，默认就没有电话
		     sendIntent.putExtra("sms_body","尊敬的"+water.getName()+"用户:你本月用水量为:"+userwater); 
		     sendIntent.setType("vnd.android-dir/mms-sms"); 
		     startActivity(sendIntent);
		}else if(item.getItemId()==(ITEM0+1)){
			showDialog(DIALOG);
		}else if(item.getItemId()==(ITEM0+2)){
			showDialog(DIALOG+2);
		}
		return false;
	}
	
	
	/**
	 * 初始化读卡
	 */
	public void initRFID(int type){
		rh=RfidHelper.getInstance();
		rh.setCardType(type);
		rh.open();
		rh.setAllNoOfTimes(1);
		rh.setTimeInterval(50);
		// 设置激活读卡器后等待的时间.sdk默认10
		rh.setPingTimeInterval(10);
	}

	@Override
	protected Dialog onCreateDialog(int id) {

		 Dialog dialog=null;
	        switch (id) {
	        case DIALOG:
	            Builder builder=new android.app.AlertDialog.Builder(this);
	            //设置对话框的图标
	            builder.setIcon(R.drawable.buttondraw);
	            //设置对话框的标题
	            builder.setTitle("选择读卡协议");
	            //0: 默认第一个单选按钮被选中
	            
	            builder.setSingleChoiceItems(R.array.hobby, 0, new android.content.DialogInterface.OnClickListener(){
	                public void onClick(DialogInterface dialog, int which) {
	                   xieyi=getResources().getStringArray(R.array.hobby)[which];
	                   
	                }
	            });
	            
	            //添加一个确定按钮
	            builder.setPositiveButton(" 确 定 ", new DialogInterface.OnClickListener(){
	                public void onClick(DialogInterface dialog, int which) {
	                    if(xieyi.equals("15693")){
	                    	initRFID(2);
	                    	FRIDtype=2;
	                    }else if(xieyi.equals("14443")){
	                    	initRFID(1);
	                    	FRIDtype=1;
	                    }
	                }
	            });
	            //创建一个单选按钮对话框
	            dialog=builder.create();
	            break;
	        case DIALOG+2:
	        	if(readtype.equals("终端读卡")){
	        		readdate=new String[]{"终端读卡","蓝牙读卡"};
	        	}else{
	        		readdate=new String[]{"蓝牙读卡","终端读卡"};
	        	}
	        	
	            builder=new android.app.AlertDialog.Builder(this);
	            //设置对话框的图标
	            builder.setIcon(R.drawable.buttondraw);
	            //设置对话框的标题
	            builder.setTitle("读卡方式选择");
	            //0: 默认第一个单选按钮被选中
	            
	            builder.setSingleChoiceItems(readdate, 0, new android.content.DialogInterface.OnClickListener(){
	                public void onClick(DialogInterface dialog, int which) {
	                   readtype=readdate[which];
	                 
	                   
	                }
	            });
	            
	            //添加一个确定按钮
	            builder.setPositiveButton(" 确 定 ", new DialogInterface.OnClickListener(){
	                public void onClick(DialogInterface dialog, int which) {
	                	time=System.currentTimeMillis();
	                    if(readtype.equals("蓝牙读卡")){
	                    	bluehelp.start();
	                    }else{
	                    	initRFID(FRIDtype);
	                    }
	                	isStop=true;
	                	
	                }
	            });
	            //创建一个单选按钮对话框
	            dialog=builder.create();
	            break;
	        }
	        return dialog;
	}	

	@Override
	protected void onPause() {
		
		   
		safe=new SafetyExitUtil(CopyWaterRFIDActivity.this);
		safe.start();
		
		super.onPause();
	}

	@Override
	protected void onResume() {
	   if(safe!=null){
		   safe.stop();
	   }		
		System.out.println("text onResume ");
		super.onResume();
	}

	
	Handler MyHandler=new Handler(){


		@Override
		public void handleMessage(Message msg) {
			long times=System.currentTimeMillis();
			if(times-time>12000){
				b=true;
			
				Toast.makeText(CopyWaterRFIDActivity.this,
						"读卡超时", Toast.LENGTH_SHORT).show();
				isStop=false;
				if(readtype.equals("终端读卡")){
            		pd.dismiss();
            	}else{
            	    bluehelp.close();
            	}
				return;
			}
			if (msg.what == 1) {
				b=true;
			
				if(readtype.equals("终端读卡")){
            		pd.cancel();
            	
            	}else{
            	    bluehelp.close();
            	}
				
				isupload=false;
				Toast.makeText(CopyWaterRFIDActivity.this,
						"读卡成功" + msg.obj.toString(), Toast.LENGTH_LONG).show();
				
				CopyWaterDao dao=new CopyWaterDao(CopyWaterRFIDActivity.this);
				
				List<UserWaterVO> lists=dao.queryUserWaterInfo(RFIDnumber, null,null);
				dao.close();
			
				if(lists!=null&&lists.size()>0){
					
					water=lists.get(0);
				}else{
					Toast.makeText(CopyWaterRFIDActivity.this, "此RFID卡还未绑定水表", Toast.LENGTH_LONG).show();
					return;
				}
				
				if(water==null){
					Toast.makeText(CopyWaterRFIDActivity.this, "此RFID卡还未绑定水表", Toast.LENGTH_LONG).show();
					return;
				}				
				viewdate();
				TipHelper.Vibrate(CopyWaterRFIDActivity.this, 1000);
			}
		}

	
	};
	
}
